﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using VISS.Web.Frontend;
using VISS.API.Users;
using NCT.Framework;


public partial class api_chat : System.Web.UI.Page
{
    protected UserContext userContext = new UserContext();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Request.QueryString["action"] != null)
        {
            userContext = LoginFactory.GetCurrentUser();

            if (Session["chatHistory"] == null)
            {
                Session["chatHistory"] = new Hashtable(); ;
            }
            if (Session["openChatBoxes"] == null)
            {
                Session["openChatBoxes"] = new Hashtable();
            }
            if (Session["tsChatBoxes"] == null)
            {
                Session["tsChatBoxes"] = new Hashtable();
            }
            switch (Request.QueryString["action"].ToString())
            {
                case "chatheartbeat":
                    {
                        chatHeartbeat();
                        break;
                    }
                case "sendchat":
                    {
                        sendChat();
                        break;
                    }
                case "closechat":
                    {
                        closeChat();
                        break;
                    }
                case "startchatsession":
                    {
                        startChatSession();
                        break;
                    }
            }
        }
    }
    private void chatHeartbeat()
    {
        ChatDataContext context = new ChatDataContext();

        List<Chat> messages = context.Chats.Where(p => p.to == userContext.UserKey.ToString() && p.recd == 0).OrderBy(p => p.id).ToList();

        string items = "";

        foreach (Chat message in messages)
        {
           
            if (Session["openChatBoxes"] != null && Session["chatHistory"] != null)
            {
                if (!((Hashtable)(Session["openChatBoxes"])).Contains(message.from) && ((Hashtable)(Session["chatHistory"])).Contains(message.from))
                {
                    items = ((Hashtable)(Session["chatHistory"]))[message.from].ToString();
                }
            }

            message.message = sanitize(message.message);

            items = items + "{\"s\":\"0\",\"f\":\"" + message.from.ToString() + "\",\"m\":\"" + message.message + "\"},";

            if (Session["chatHistory"] != null)
            {
                if (!((Hashtable)(Session["chatHistory"])).Contains(message.from))
                {
                    ((Hashtable)(Session["chatHistory"]))[message.from] = "";

                }
            }
            if (Session["chatHistory"] != null)
                ((Hashtable)(Session["chatHistory"]))[message.from.ToString()] += "{\"s\":\"0\",\"f\":\"" + message.from.ToString() + "\",\"m\":\"" + message.message + "\"},";
            if (Session["tsChatBoxes"] != null)
                ((Hashtable)(Session["tsChatBoxes"]))[message.from.ToString()] = null; // Unset means clear the session value
            if (Session["openChatBoxes"] != null)
                ((Hashtable)(Session["openChatBoxes"]))[message.from.ToString()] = message.sent;


        }
        if (Session["openChatBoxes"] != null)
        {
            Hashtable openChatBoxesArray = (Hashtable)(Session["openChatBoxes"]);
            for (int i = 0; i < openChatBoxesArray.Count; i++)
            {
                int chatbox = i;
                if (openChatBoxesArray[i] != null)
                {
                    DateTime time = (DateTime)(openChatBoxesArray[i]);
                    string timeval = "";
                    TimeSpan Now = (TimeSpan)(DateTime.Now - time);
                    timeval = time.ToString("g:iA M dS");
                    string message = "Sent at " + timeval;

                    if (Now.Minutes > 180)
                    {
                        items += "{\"s\":\"2\",\"f\":\"" + chatbox.ToString() + "\",\"m\":\"" + message + "\"";
                        if (((Hashtable)(Session["chatHistory"]))[chatbox] != null)
                        {
                            ((Hashtable)(Session["chatHistory"]))[chatbox] = "";
                        }
                        ((Hashtable)(Session["chatHistory"]))[chatbox] += "\"s\":\"2\",\"f\":\"" + chatbox.ToString() + "\",\"m\":\"" + message + "\"";
                        ((Hashtable)(Session["tsChatBoxes"]))[chatbox] = "1";
                    }
                }
            }
        }

        List<Chat> list = context.Chats.Where(p => p.to == userContext.UserKey.ToString() && p.recd == 0).ToList();

        foreach (Chat obj in list)
        {
            obj.recd = 1;
            context.SubmitChanges();

        }

        if (items != string.Empty)
        {
            items = items.Substring(0, items.Length - 1);
        }

        Response.Clear();
        Response.Write("{ ");
        Response.Write("\"items\":[" + items + "]");
        Response.Write(" }");
        Response.End();
    }
    private string sanitize(string text)
    {
        //text = htmlspecialchars(text, ENT_QUOTES); // Convert the html special characters
        text = text.Replace("\n\r", "\n");
        text = text.Replace("\r\n", "\n");
        text = text.Replace("\n", "<br>");
        return text;
    }
    private string chatBoxSession(int chatbox)
    {

        string items = "";

        if (((Hashtable)(Session["chatHistory"]))[chatbox] != null)
        { // Check the Session variable
            items = ((Hashtable)(Session["chatHistory"]))[chatbox].ToString();
        }

        return items;
    }
    private void sendChat()
    {
        string from = userContext.UserKey.ToString(); // Assign Session user name value to $from value
        string to = Request["to"]; // Assign POST FORM 'To' value to $to value}
        string message = Request["message"]; // Assign POST FORM 'message' value to $message value

        if (Session["openChatBoxes"] != null)
            ((Hashtable)(Session["openChatBoxes"]))[to] = DateTime.Now.ToString("Y-m-d H:i:s");

        string messagesan = sanitize(message);
        if (Session["chatHistory"] != null)
        {
            if (((Hashtable)(Session["chatHistory"])).Contains(Request["to"]))
            {
                ((Hashtable)(Session["chatHistory"]))[to] = "";
                //((Hashtable)(Session["chatHistory"]))[getIndexOf(((Hashtable)(Session["chatHistory"])), Request["to"])] = "";
            }
        }
        if (Session["chatHistory"] != null)
            ((Hashtable)(Session["chatHistory"]))[to] += "\"s\":\"1\",\"f\":\"{" + to + "}\",\"m\":\"{" + messagesan + "}\"";
        if (Session["tsChatBoxes"] != null)
            ((Hashtable)(Session["tsChatBoxes"]))[to] = null;

        /* Add Insert Query here*/

        Chat chatObj = new Chat();
        chatObj.to = to;
        chatObj.from = from;
        chatObj.message = message;
        chatObj.sent = DateTime.Now;
        chatObj.recd = 0;

        ChatDataContext context = new ChatDataContext();

        context.Chats.InsertOnSubmit(chatObj);

        context.SubmitChanges();
        Response.Clear();
        Response.Write("1");
        Response.End();
    }
    private void closeChat()
    {
        int chatbox = 1; //value of chatbox
        try
        {
            ((Hashtable)(Session["openChatBoxes"]))[chatbox] = null;
        }
        catch
        {
        }
        Response.Clear();
        Response.Write("1");
        Response.End();
    }
    private void startChatSession()
    {
        string items = "";
        if (Session["openChatBoxes"] != null)
        { // Check the Session variable
            Hashtable openChatBoxesArray = (Hashtable)(Session["openChatBoxes"]);
            for (int i = 0; i < openChatBoxesArray.Count; i++)
            { // Loop the session array
                items += chatBoxSession(i); // Append to Items variable
            }
        }
        if (items != string.Empty)
        {
            items = items.Substring(0, items.Length - 1);
        }
        Response.Clear();
        Response.Write("{ ");
        Response.Write("\"username\": \"" + userContext.UserKey.ToString() + "\","); // Display the Username Which is set in the session
        Response.Write("\"items\": [");
        Response.Write(items);
        Response.Write("]");
        Response.Write("}");
        Response.End();
    }

    

}
